<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/3
 * Time: 11:18
 */

namespace app\admin\controller;

//订单列表
use app\Model\AdminModel;
use app\Model\FlagshipModel;
use app\Model\GoodsModel;
use app\Model\OrderActionModel;
use app\Model\OrderGoodsModel;
use app\Model\OrderModel;
use app\Model\PluginModel;
use app\Model\RegionModel;
use app\Model\SpecGoodsPriceModel;
use app\Model\UsersModel;
use think\Db;

class Order extends Common
{
    /*
     * 订单列表页
     */
    public function index()
    {

        $postData = input('get.');
        $where = [];
        $time=[0,time()];
        //筛选
        if (isset($postData['consignee'])){
            if ($postData['consignee']!=-1&&$postData['consignee']!=''){//收货人
                $where['consignee'] = ['LIKE', '%'.$postData['consignee'].'%'];
            }
            if ($postData['order_sn']){//订单编号
                $where['order_sn'] = ['=', $postData['order_sn']];
            }
            if ($postData['pay_status']!=-1&&$postData['pay_status']!=''){//支付状态
                $where['pay_status'] = ['=', $postData['pay_status']];
            }

            if ($postData['pay_code']!=-1&&$postData['pay_code']!=''){//支付方式
                $where['pay_code'] = ['=', $postData['pay_code']];
            }
            if ($postData['shipping_status']!=-1&&$postData['shipping_status']!=''){//发货状态
                $where['shipping_status'] = ['=', $postData['shipping_status']];
            }
            if ($postData['order_status']!=-1&&$postData['order_status']!=''){//订单状态
                $where['order_status'] = ['=', $postData['order_status']];
            }

            if ($postData['add_time']){//下单时间
                $postData['add_time']=explode(" - ", $postData['add_time']);//时间分割成[0]第一个 [1]第二个 取中间值
                $time[0]=strtotime($postData['add_time'][0]);
                $time[1]=strtotime($postData['add_time'][1])+86399;
            }
        }

        $getWithdrawals= OrderModel::
//        order('status','asc')//提现状态0申请中1申请成功2申请失败
        where($where)//筛选
        ->whereTime('add_time', 'between', [$time[0], $time[1]])//筛选时间
        ->order('add_time','desc')
        ->paginate(null,false,['query'=>request()->param()]);
        $data['data'] = $getWithdrawals;
        $order = new OrderModel();
        $data['order_status']=$order->getStatus();
        $this->getConAndAct('order');
        return view('index',$data);
    }


    /*
     * 添加订单页面
     */
    public function add()
    {
        $getRegion=RegionModel::where('level','=',1)->select();
        $data['province']=$getRegion;//省数据传入view
        $this->getConAndAct('order');//表明属于哪个主目录
        //选择商品
        session('order_goods_set',0);
        $data['comm']=$this->goodsEndSpec();//商品列表（包含不同规格）
        return view('add',$data);
    }

    /*
     * 根据手机号搜索用户（会员信息）
     * 打印出符合条件的会员信息
     */
    public function search()
    {
        $postData=input('post.');
        $where['mobile']=['LIKE','%'.$postData['name'].'%'];
        $gerUser=UsersModel::where($where)->select();
//        dump($gerUser->toArray());die();
//        return setDatabase($gerUser,'',$gerUser);
        foreach($gerUser as $key => $val)
        {
            echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
        }
        exit();

    }
    /*
     * 根据省市县id获取name
     * $postData(数据)
     */
    public function regioName($postData)
    {
        $province=  RegionModel::where('id',$postData['province'])->value('name');
        $city=  RegionModel::where('id',$postData['city'])->value('name');
        $district=  RegionModel::where('id',$postData['district'])->value('name');
        $add=$province.$city.$district;
        return $add;
    }


    /*
     * 新增订单
     */
    public function addData()
    {
        $postData=input('post.');
//        $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
        $postData['shipping_name']='顺丰'; //PluginModel::where('code','=',$postData['shipping_code'])->value('name');//物流方式name
        $postData['pay_name'] = '余额支付';//    PluginModel::where('code','=',$postData['pay_code'])->value('name');// 支付方式
        $money=0;//商品总价
        foreach ($postData['goods'] as $k=>$v){

            $where=['goods_id'=>$v['goods_id']];
            //判断该商品是否有规格
            if ($v['key']=='undefined'){//没有规格
                $moneyq= GoodsModel::where($where)->value('shop_price');//商品本店价
            }else{//有规格
                $moneyq=SpecGoodsPriceModel::where($where)->where('key',$v['key'])->value('price');//规格本店价
            }
            $moneyq = $moneyq*$v['num'];//本店价*数量
            $money+=$moneyq;//商品总价
        }

        $postData['goods_price']=$money;//商品总价
        $postData['shipping_price']= $this->logistics($postData['goods']);//计算物流费用  参数：商品【】、数量【】、物流方式、
        $postData['order_amount']= $money+$postData['shipping_price']; // 应付金额（去除积分、优惠、余额 所需支付的金额 目前不需要，金额+物流）
        $postData['total_amount']   = $money; // 订单总价（目前只需要金额）
            //去除订单表不需要的字段
        if (!isset($postData['order_id'])){//新增（有订单id）
            $postData['address']=$this->regioName($postData).$postData['address'];

            unset($postData['province']);
            unset($postData['city']);
            unset($postData['district']);
            unset($postData['name01']);//去除name01
              $postData['add_time']=time();//订单添加时间
              $postData['order_sn']=date('YmdHis').rand(1000,9999);//订单编号
        }
        unset($postData['goods_id']);//去除商品id
        $goods_data=$postData['goods'];
        unset($postData['goods']);//去除商品数据
        if (isset($postData['order_id'])){//编辑
            OrderModel::where('order_id','=',$postData['order_id'])->update($postData);//订单表编辑
            OrderGoodsModel::where('order_id','=',$postData['order_id'])->delete();//删除订单与商品链接表旧数据（新增时添加的商品）

            $setOrder=$postData['order_id'];
        }else{
            $setOrder = OrderModel::insertGetId($postData);//新增订单 获取id
        }
        setDatabaseDef($setOrder,'订单表操作失败');

        if($setOrder){
            $orderArray=[];
            foreach ($goods_data as $k=>$v){
                $goods=GoodsModel::find($v['goods_id']);
                $val['order_id'] = $setOrder;//自增订单id
                $val['goods_id'] = $v['goods_id'];//商品id
                $val['goods_name']=$goods->goods_name;//商品名称
                $val['goods_sn']=$goods->goods_sn;//商品编号
                $val['goods_num']=$v['num'];//数量
                $val['market_price']=$goods['market_price'];//市场价
                $val['goods_price']=$goods->shop_price;//本店价
//                $val['cost_price']=$v['cost_price'];//商品成本价
                $val['spec_key']='';//商品规格key
                $val['spec_key_name']='';//规格对应中文
                $val['member_goods_price']=$goods->shop_price;//会员折扣价（管理员添加无需折扣）
                if ($v['key']!='undefined'){//有规格
                    $spec_data=SpecGoodsPriceModel::where('goods_id',$v['goods_id'])->where('key',$v['key'])->find();
                    $val['spec_key']=$spec_data->key;//商品规格key
                    $val['spec_key_name']=$spec_data->key_name;//规格对应中文
                    $val['goods_price']=$spec_data->price;//规格本店价

                }
//                $val['give_integral']=$v['give_integral'];//购买商品赠送积分
//                $val['member_goods_price']=$v['member_goods_price'];//会员折扣价

//                $val['bar_code']=$v['bar_code'];//条码
//                $val['is_comment']=$v['is_comment'];//是否评价
//                $val['prom_type']=$v['prom_type'];//0 普通订单,1 限时抢购, 2 团购 , 3 促销优惠
//                $val['prom_id']=$v['prom_id'];//活动id
//                $val['is_send']=$v['is_send'];//0未发货，1已发货，2已换货，3已退货
//                $val['delivery_id']=$v['delivery_id'];//发货单id
                array_push($orderArray,$val);
            }
            $serOrderGoods=OrderGoodsModel::insertAll($orderArray);//订单与商品链接表添加数据
            setDatabaseDef($serOrderGoods,'订单与商品链接表添加失败');
        }
        return retJson('',200,'订单操作成功');
    }

    /*
     * 编辑订单页面
     */
    public function edit()
    {

        $getData=input('get.');
        $data['order']=OrderModel::find($getData['order_id']);   //订单信息

        if ($data['order']->order_status!=0){$this->error('只有未确定订单可以编辑');};

//       dump($getGoods->toArray());die();
        $data['comm']=$this->goodsEndSpec();//商品列表（包含不同规格）
        $data['goods']=OrderGoodsModel::where('order_id','=',$getData['order_id'])->select();  //已有商品
        return view('edit',$data);
    }

    /*
     * 订单操作(详情)页面
     */
    public function particular()
    {
        //订单信息
        $getData = input('get.');
        $getOrder = OrderModel::find($getData['order_id']);//指定id的订单信息
        $data['order']=$getOrder;
        if ($getOrder->order_cal==1){
            $data['user']=FlagshipModel::find($getOrder->user_id);//加盟商信息
        }else{
            $data['user']=UsersModel::find($getOrder->user_id);//会员信息
        }
//        $data['leve']=$this->user_leve($data['user']->level);
        $data['goods']=$this->goods($getData['order_id']);//根据订单id查找该订单商品

        $data['orderAction']=OrderActionModel::where('order_id','=',$getData['order_id'])->order('log_time',"desc")
            ->alias('o_a')
            ->join('tp_admin a','o_a.action_user=a.admin_id')
            ->select();//操作记录
        $data['status']=OrderModel::RrderToNames();//订单状态(中文)
        $data['orderButton']=buttonData($getOrder);//操作按钮（未确认=>确认，未支付=》支付，未发货=》发货）
        //用户会员等级信息
        return view('particular',$data);
    }
    
    /*
     * 订单操作
     */
    public function setOrder()
    {

        $postData=input('post.');
        $order = OrderModel::find($postData['order_id']);
        $action = OrderModel::RrderToName($postData['order_field'],$postData['field_val']);//订单操作（中文）
        $this->setOrderC($order,$postData['order_field'],$postData['field_val'],"订单".$action,$postData['note']);//订单操作
        return retJson('',200,"订单".$action);

    }

    /*
     * 订单价格调整页面（调整物流费、订单价）
     */
    public function editprice()
    {
        $getData=input('get.');
        $getOrder = OrderModel::find($getData['order_id']);//指定id的订单信息
        if ($getOrder->order_status!=0){
                $this->error('已确定订单不可调整');
        }
        $data['order']=$getOrder;
        return view('editprice',$data);
    }

    /*
     * 订单价格调整
     */
    public function editOrder()
    {

        $getOrder = OrderModel::find(input('post.order_id'));//指定id的订单信息
        if ($getOrder->order_status!=0){
            return retJson('',201,'已确定订单不可调整');
        }
        $postData=[
            'order_id'=>input('post.order_id'),//订单id
            'shipping_price'=>input('post.shipping_price'),//运费
            'discount'=>input('post.setdiscount'),//调整金额
        ];
        //                          订单应付金额            +     价格调整           +    物流费
        $postData['order_amount']= $getOrder->total_amount   + $postData['discount'] +  $postData['shipping_price'];//计算订单应付款金额
        $setOrder = OrderModel::where('order_id','=',$postData['order_id'])->update($postData);
        return setDatabase($setOrder);
    }
    
    /*
     * 订单日志
     */
    public function orderlog()
    {
        $postData = input('get.');
        $where = [];
        $time=[0,time()];
        //筛选
        if (isset($postData['order_sn'])){
            if ($postData['order_sn']){//订单编号
                $where['o.order_sn'] = ['LIKE', '%'.$postData['order_sn'].'%'];
            }
            if ($postData['user_name']!=-1){//操作人（管理员name）
                $where['action_user'] = ['=', $postData['user_name']];
            }

            if ($postData['log_time']){//操作时间
                $postData['log_time']=explode(" - ", $postData['log_time']);//时间分割成[0]第一个 [1]第二个 取中间值
                $time[0]=strtotime($postData['log_time'][0]);
                $time[1]=strtotime($postData['log_time'][1])+86399;
            }
        }
        $getOrderAction = OrderActionModel::alias('o_a')
            ->join('tp_order o','o_a.order_id=o.order_id')//连接订单表
            ->where($where)
            ->whereTime('log_time', 'between', [$time[0], $time[1]])//筛选时间
//            ->join('tp_admin a','o_a.action_user=a.admin_id')
            ->order("log_time","desc")
            ->paginate(null,false,['query'=>request()->param()]);
        $data['admin']=AdminModel::column('user_name','admin_id');//管理员
//        dump($data['admin']);die();

        $data['data']=$getOrderAction;
        $this->getConAndAct('order');
        return view('orderlog',$data);
    }

    /*
     * 打印订单页
     */
    public function printOrder()
    {
        $getData=input('get.');

        $getOrder=OrderModel::find($getData['order_id']);//订单信息（单）
        $data['order']=$getOrder;
        $data['province']=RegionModel::find($getOrder->province);//省
        $data['city']= RegionModel::find($getOrder->city);//市
        $data['district']= RegionModel::find($getOrder->district);//县
        $data['order_goods'] = OrderGoodsModel::where('order_id','=',$getData['order_id'])->select();//商品（订单内的）
        return view('printOrder',$data);
    }
    /*
     * 删除订单
     */
    public function del()
    {
        $postData = input('post.');
        $delOrderGoods=OrderGoodsModel::where('order_id','=',$postData['id'])->delete();
        $delOrder = OrderModel::destroy($postData['id']);
        return setDatabase($delOrder);
    }
}